package com.ys.controller.api.report;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.config.MenuId;
import com.ys.entity.report.ReFinanceExamine;
import com.ys.entity.report.TcoBusinessDataStat;
import com.ys.entity.sys.YsCol;
import com.ys.service.report.TcoBusinessDataStatService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tcoBusinessDataStat")
public class ApiInterTcoBusinessDataStatController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcoBusinessDataStatController.class);
    private static Long MENU_ID = MenuId.TCO_BusinessDataStat;

    @Autowired
    private CommonApiService<TcoBusinessDataStat> commonApiService;

    @Autowired
    private TcoBusinessDataStatService tcoBusinessDataStatService;
    /**
     * 设置查询的cond的sql设置
     * @param cond
     * @return
     */
    public TcoBusinessDataStat setSeachSql(TcoBusinessDataStat cond){
        cond.addField(" FORMAT(DATEADD(day, -1, A.CreateTime), 'yyyy-MM-dd') AS countTime");//统计时间

        cond.addLeftJoin("[kjecp_report].[dbo].TCO_BusinessDataGs B ON B.Vgsbm = A.Vgsbm")//有进行配置才显示
                .where("B.Status = 1");

        //排序
        cond.setOrderby("A.CountMonth DESC,A.Vgsbm ASC");
        return  cond;
    }



    //处理返回的数据，将JSON类型转换成具体返回字段
    public List<Map<String, Object>> setList(List<Map<String, Object>> resDate) {
        List<Map<String, Object>> newList = new ArrayList<>();
        for(Map<String, Object> infoMap:resDate){
            if(infoMap.get("saleAmount")!=null && !"".equals(infoMap.get("saleAmount"))){//销售金额
                infoMap.put("saleAmount", String.format("%.2f", (BigDecimal) infoMap.get("saleAmount")));
            }
            if(infoMap.get("orderNumByDay")!=null && !"".equals(infoMap.get("orderNumByDay"))){//日均数量
                infoMap.put("orderNumByDay", String.format("%.2f", (BigDecimal) infoMap.get("orderNumByDay")));
            }
            if(infoMap.get("shopBackAmount")!=null && !"".equals(infoMap.get("shopBackAmount"))){//店铺回款
                infoMap.put("shopBackAmount", String.format("%.2f", (BigDecimal) infoMap.get("shopBackAmount")));
            }
            if(infoMap.get("purchaseCostAmount")!=null && !"".equals(infoMap.get("purchaseCostAmount"))){//采购费用
                infoMap.put("purchaseCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("purchaseCostAmount")));
            }
            if(infoMap.get("storageCostAmount")!=null && !"".equals(infoMap.get("storageCostAmount"))){//仓储费用
                infoMap.put("storageCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("storageCostAmount")));
            }
            if(infoMap.get("transportCostAmount")!=null && !"".equals(infoMap.get("transportCostAmount"))){//运输费用
                infoMap.put("transportCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("transportCostAmount")));
            }
            if(infoMap.get("businessCostAmount")!=null && !"".equals(infoMap.get("businessCostAmount"))){//运营费用
                infoMap.put("businessCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("businessCostAmount")));
            }
            if(infoMap.get("erpSurplusAmount")!=null && !"".equals(infoMap.get("erpSurplusAmount"))){//ERP余额
                infoMap.put("erpSurplusAmount", String.format("%.2f", (BigDecimal) infoMap.get("erpSurplusAmount")));
            }
            if(infoMap.get("awsSurplusAmount")!=null && !"".equals(infoMap.get("awsSurplusAmount"))){//亚马逊余额
                infoMap.put("awsSurplusAmount", String.format("%.2f", (BigDecimal) infoMap.get("awsSurplusAmount")));
            }
            if(infoMap.get("stockProductNum")!=null && !"".equals(infoMap.get("stockProductNum"))){//库存总额
                infoMap.put("stockProductNum", String.format("%.2f", (BigDecimal) infoMap.get("stockProductNum")));
            }
            if(infoMap.get("estimateAmount")!=null && !"".equals(infoMap.get("estimateAmount"))){//预估价值
                infoMap.put("estimateAmount", String.format("%.2f", (BigDecimal) infoMap.get("estimateAmount")));
            }
//            if(infoMap.get("yearOrderNum")!=null && !"".equals(infoMap.get("yearOrderNum"))){//年订单数
//                infoMap.put("yearOrderNum", String.format("%.2f", (BigDecimal) infoMap.get("yearOrderNum")));
//            }
            if(infoMap.get("yearSaleAmount")!=null && !"".equals(infoMap.get("yearSaleAmount"))){//年销售额
                infoMap.put("yearSaleAmount", String.format("%.2f", (BigDecimal) infoMap.get("yearSaleAmount")));
            }
            if(infoMap.get("yearOrderNumByDay")!=null && !"".equals(infoMap.get("yearOrderNumByDay"))){//年日均数量
                infoMap.put("yearOrderNumByDay", String.format("%.2f", (BigDecimal) infoMap.get("yearOrderNumByDay")));
            }
            if(infoMap.get("yearShopBackAmount")!=null && !"".equals(infoMap.get("yearShopBackAmount"))){//年店铺回款
                infoMap.put("yearShopBackAmount", String.format("%.2f", (BigDecimal) infoMap.get("yearShopBackAmount")));
            }
            if(infoMap.get("yearPurchaseCostAmount")!=null && !"".equals(infoMap.get("yearPurchaseCostAmount"))){//年采购费用
                infoMap.put("yearPurchaseCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("yearPurchaseCostAmount")));
            }
            if(infoMap.get("yearStorageCostAmount")!=null && !"".equals(infoMap.get("yearStorageCostAmount"))){//年仓储费用
                infoMap.put("yearStorageCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("yearStorageCostAmount")));
            }
            if(infoMap.get("yearTransportCostAmount")!=null && !"".equals(infoMap.get("yearTransportCostAmount"))){//年运输费用
                infoMap.put("yearTransportCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("yearTransportCostAmount")));
            }
            if(infoMap.get("yearBusinessCostAmount")!=null && !"".equals(infoMap.get("yearBusinessCostAmount"))){//年运营费用
                infoMap.put("yearBusinessCostAmount", String.format("%.2f", (BigDecimal) infoMap.get("yearBusinessCostAmount")));
            }
            newList.add(infoMap);
        }
        return newList;
    }

    /**
     * 查询
     */
    @RequiresPermissions("tcoBusinessDataStat:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(Model model, HttpServletRequest request, HttpServletResponse response,
                                 @ModelAttribute TcoBusinessDataStat cond
    ){
        try {
            cond = setSeachSql(cond);

            LayuiTableVoJA searchList =  commonApiService.searchLay(cond);
            //获取
            JSONArray tableVoJAData = searchList.getData();

            //转换
            List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
            List<Map<String, Object>> resListNew = new ArrayList();
            resList.forEach(item-> resListNew.add(item));
            List<Map<String, Object>> resultList = new ArrayList();
            //处理数据
            if(resListNew.size()>0) {
                resultList = setList(resListNew);
            }
            JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
            searchList.setData(jsonArray);


            return searchList;
        }catch (Exception e){
            logger.error("查询出错：",e.getMessage(),e);
            LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
            tableVoJA.setCode(1);
            tableVoJA.setMsg("查询出错，请稍后重试！");
            return tableVoJA;
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcoBusinessDataStat cond){
        try {
            cond.setPage(0).setSize(999999);
            cond = setSeachSql(cond);
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MENU_ID)
                    .where("A.Code != 'ope'")
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<ReFinanceExamine> util = new ExportExcelUtils<>(new ReFinanceExamine());
            String toFilePath = util.exportExcel(listData, listField, "运营数据统计表");
            UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }




    /**
     * 编辑亚马逊余额
     */
    @RequiresPermissions("tcoBusinessDataStat:editAwsSurplusAmount")
    @RequestMapping("/editAwsSurplusAmount")
    @ResponseBody
    public R editAwsSurplusAmount(HttpServletRequest request, @RequestParam Map<String, Object> params){
        try {
            if(params.get("awsSurplusAmount")==null || "".equals(params.get("awsSurplusAmount").toString())){
                return R.error("亚马逊余额为空");
            }
            return tcoBusinessDataStatService.editAwsSurplusAmount(Long.parseLong(params.get("id").toString()),params.get("awsSurplusAmount").toString());
        } catch (Exception e) {
            logger.error("出错：",e.getMessage(),e);
            return R.error(e.getCause().getMessage());
        }
    }


}